# -*- coding: utf-8 -*-

import sys,os,xmpp,time,select
from geopy import geocoders

class imn_xmpp:
    
    def __init__(self):
        self._username = ''
        self._password = ''
        self._server = '@jabber.org'
        self._client = None
        self._buddy_list = []
        self._pos = (0,0)
        self._loc = ''
        self._bot = 'imnext_bot@jabber.org'
        self._next_list = []
        self.__google_api_key ="ABQIAAAAwtsNcJLMTD8UKmhctULKkBRVZIMnq36JdECjF5yaoaN8a7L-2xSxgBJD0C4QoFL3DIDhDxH3j81M1g"
        

    def init( self, username, password, msg_arr_func, update_next_list ):
        self._username = username
        self._password = password

        self._jid = xmpp.protocol.JID(self._username + self._server)
        self._client = xmpp.Client( self._jid.getDomain() )

        self._msg_arr_func = msg_arr_func
        self._sign_update_next_list = update_next_list


    def set_location(self, loc ):
        g = geocoders.Google(self.__google_api_key)
        try:
            self._loc, (lat, long) = g.geocode(loc)
            self.set_position( (lat, long) )
        except:
            self._loc = ''
            self.set_position( (0,0) )
            return False
        
        return True


    def get_location(self):
        return self._loc

        
    def set_position(self, pos ):       
        self._pos = pos


    def get_username(self):
        return self._username


    def get_password(self):
        return self._password


    def get_msg_arr_func(self):
        return self._msg_arr_func


    def get_sign_update_next_list(self):
        return self._sign_update_next_list
    

    def get_position(self):
        return self._pos

    
    def connect(self):
        con = self._client.connect()
        if not con:
            sys.stderr.write('Não pude conectar.\n')
            return False

        auth = self._client.auth( self._jid.getNode(),
                                  self._password,
                                  resource=self._jid.getResource())
        if not auth:
            sys.stderr.write('Não pude autentica-lo.\n')
            return False

        self._client.RegisterHandler('message', self.message_arrived )

        self._client.sendInitPresence()

        return True


    def disconnect(self):
        try :
            self._client.disconnected()
            return False
        except:
            self._client = None
            return True

    def send_message( self, receiver, message ):
        self._client.send(xmpp.protocol.Message(receiver,message))
        

    def is_initiated(self):
        if self._client == None:
            return False
        else:
            return True
        
    def is_connected(self):
        return self._client.isConnected()

    
    def add_friend( self, new_friend ):
        self._buddy_list.append( new_friend )

        
    def rm_friend( self, old_friend ):
        try:
            self._buddy_list.remove( old_friend )
        except:
            return False
        return True

    
    def get_friends_list( self ):
        list_copy = self._buddy_list
        return list_copy

    
    def get_next_list( self ):
        return self._next_list

    
    def register_within_imnext_bot(self):
        command = "register_position " + str(self._pos[0]) + " " + str(self._pos[1])
        
        self.send_message( self._bot, command )


    def message_arrived( self, con, event ):
        type = event.getType()
        fromjid = event.getFrom().getStripped()
        if fromjid == self._bot:
            self.parse_bot_msg( event.getBody() )
        elif type in ['message', 'chat', None]:
            self._msg_arr_func(fromjid, event.getBody())


    def parse_bot_msg( self, msg ):

        if msg.find(' ')+1:
            command_args=msg.split(' ')
            command = command_args[0]
            args = command_args[1:]
        else:
            command,args=msg,''

        cmd=command.lower()

        if cmd == 'update_next_list':
            self._next_list = args
            self._sign_update_next_list()
